var express     = require('express');
var router      = express.Router();
var multer      = require('multer');
const path      = require('node:path');
const password  = require(path.join(__dirname, '../utils/password'));
const database  = require(path.join(__dirname, '../utils/database'));

var uploader    = multer();

router.get('/list', async function(request, response) {
    var users = await database.query(
        "SELECT `id`,`name`,`username`,`created_at` FROM `user` WHERE `deleted_at` IS NULL ORDER BY `id` DESC",
        []
    ).then((results, fields) => {
        return results;
    });

    response.json(users);
});

router.post('/create', uploader.none(), async function(request, response) {
    var pwd     = await password.encrypt(request.body.password);
    var result  = await database.query(
        "INSERT INTO `user`(`name`,`username`,`password`,`created_at`) VALUES(?, ?, ?, ?)",
        [request.body.name, request.body.username, pwd, new Date()]
    ).then((results,fields) => {
        return results.affectedRows > 0;
    });
    response.json({state: result});
});

router.post('/update', async function(request, response) {
    var result  = await database.query(
        "UPDATE `role` SET `name`=? WHERE `id`=?", 
        [request.body.name, request.body.id]
    ).then((results, fields) => {
        return results.affectedRows > 0;
    });

    response.json({state: result});
});

router.post('/remove', uploader.none(), async function(request, response) {
    var result  = await database.query(
        "UPDATE `user` SET `deleted_at`=? WHERE `id`=?",
        [new Date(), request.body.id]
    ).then((results, fields) => {
        return results.affectedRows > 0;
    });

    response.json({state: result});
});

router.get('/:id', async function(request, response) {
    var users = await database.query(
        "SELECT `id`,`name`,`username`,`avatar` FROM `user` WHERE `id`=?",
        [request.params.id]
    ).then((results, fields) => {
        return results;
    });

     response.json(users.length === 1 ? users[0] : null);
});

module.exports = router;
